Category Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
/**
* Get the comments for the blog post.
*/
public function products()
{
return $this->hasMany(Product::class);
}
}
Product Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'name', 'price'
];
}
withSum() in cotroller
namespace App\Http\Controllers;
use App\Models\Category;
class SignaturePadController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$categories = Category::select("id", "name")
->withSum('products', 'price')
->get()
->toArray();
dd($categories);
}
}
Output
Array
(
[0] => Array
(
[id] => 1
[name] => Mobile
[products_sum_price] => 330
)
[1] => Array
(
[id] => 2
[name] => Laptop
[products_sum_price] => 410
)
)
withCount() in controller
namespace App\Http\Controllers;
use App\Models\Category;
class SignaturePadController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index()
{
$categories = Category::select("id", "name")
->withCount('products')
->get()
->toArray();
dd($categories);
}
}
Output
Array
(
[0] => Array
(
[id] => 1
[name] => Mobile
[products_count] => 3
)
[1] => Array
(
[id] => 2
[name] => Laptop
[products_count] => 2
)
)